package test4;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-12-19
 * Time: 10:20
 */
public class Main {
    public static void main(String[] args) {
        int arr[] = {6, 12, 458, 5, 4, 28, 19, 1230, 9, 47};
        countSort(arr,10);
        System.out.println(Arrays.toString(arr));
    }
    public static void countSort( int []arr,int len) {
        int min = arr[0];
        int max = arr[0];
        //step1: 先找最大值和最小值确定范围
        for (int i = 1; i <len; i++) {
            if( arr[i] > max) {
                max = arr[i];
            }
            if( arr[i] < min) {
                min = arr[i];
            }
        }
        int range = max - min + 1;

        //step2: 创建count数组
        int [] count = new int[range];

        //step3: 遍历arr数组,进行计数
        for (int i=0; i<len; i++) {
            count[ arr[i] - min ] ++;
        }

        //step4: 计数完成 , 遍历count数组 , 将array数组进行更新
        int index = 0;
        for (int i = 0; i < range; i++) {
            while( count[i] >0) {
                arr[index++] = i + min;    //此时 ,count数组的下标 + 范围 就是原来数组的值
                count[i]--;                  //相同的元素放在一起, 直到计数为0
            }
        }
    }
}
